# coding:utf-8
import re
import os
import datetime
import json
import pymysql, sqlite3

from my_sql_model.sql_model_test import ConnSql

# temp_path = r"D:\htg\demo\my_demo\my_server\template\index.html"
server_root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class MyApp(ConnSql):
    def __init__(self, environ, start_respone):
        self.environ = environ
        self.start_respone = start_respone
        super().__init__()  # 继承sqlist3 数据库的类

    def read_template(self, temp_file):
        # 读取模板文件
        # print(server_root_path)
        temp_path = r'{}\template\{}'.format(server_root_path, temp_file)
        with open(temp_path, 'r', encoding='UTF-8') as f:
            # print(f.read())
            return f.read()

    def read_static(self, path):
        # 读取静态文件
        status = '200 OK'
        response_headers = [('Content-type', 'application/javascript')]
        self.start_respone(status, response_headers)

        static_path = r'{}\{}'.format(server_root_path, path)
        with open(static_path, 'r') as f:
            return f.read()

    # 显示首页数据
    def get_index(self):
        # 先把响应头准备好
        status = '200 OK'
        response_headers = [('Content-type', 'text/html')]
        self.start_respone(status, response_headers)
        # 链接sqlist3数据库
        self.conn_db()

        # 显示数据库里面的表格
        tables = self.show_table()
        # print(tables)
        table_info = ''
        for table in tables:
            # print(table)
            table_info += """
                <li>{}</li>
            """.format(table)

        # 显示users 表的信息
        users_sql = '''select * from users'''
        user_result = self.search_info(search_sql=users_sql)
        my_users_info = ''
        for r_reslut in user_result:
            # print(r_reslut)
            try:
                my_users_info += """
                    <li>{}----{}</li>
                """.format(r_reslut[0], r_reslut[1])
            except Exception as ex:
                print('Exception is {}'.format(ex))
                my_users_info += """         
                        <li>user info----no data</li>
                    """
        # 显示test_info 表的信息
        test_sql = '''select * from test_info'''
        test_result = self.search_info(search_sql=test_sql)
        my_test_info = ''
        for e_result in test_result:
            # print(e_result)
            try:
                my_test_info += """
                            <li>{}--{}---{}---{}---{}</li>
                        """.format(e_result[0], e_result[1], e_result[2], e_result[3], e_result[4])
            except Exception as ex:
                print('Exception is {}'.format(ex))
                my_test_info += """
                    <li>test info--no data</li>
                """
        # 断开sqlist3数据库链接
        self.close_db()

        # 拼接响应体
        replace_content = 'my index display ok!!'
        temp_content = self.read_template(temp_file='index.html')
        respones_content = temp_content.replace('{%my_index_content%}', replace_content)
        respones_content = respones_content.replace('{%my_table_info%}', table_info)
        respones_content = respones_content.replace('{%my_user_info%}', my_users_info)
        respones_content = respones_content.replace('{%my_test_info%}', my_test_info)
        return respones_content
        # return "你好"

    # 显示编辑页面
    def show_edit_page(self):
        # 先准备响应头
        status = '200 OK'
        response_headers = [('Content-type', 'text/html')]
        self.start_respone(status, response_headers)

        # 拼接响应体
        response_content = self.read_template(temp_file='show_edit_page.html')
        return response_content

    def no_find(self):
        status = '404 NOT FIND'
        response_headers = [('Content-type', 'text/plain')]
        self.start_respone(status, response_headers)
        respones_content = 'NOT FIND'
        yield respones_content

    def test_info_update(self):
        status = '200 OK'
        response_headers = [('Content-type', 'text/html')]
        self.start_respone(status, response_headers)
        print(self.environ['QUERY_STRING'])

        uuttype = ''
        sn = ''
        product_name = ''
        try:
            uuttype_str = self.environ['QUERY_STRING'].split('&')[0]
            uuttype = uuttype_str.split('=')[1]
            sn_str = self.environ['QUERY_STRING'].split('&')[1]
            sn = sn_str.split('=')[1]
            product_name_str = self.environ['QUERY_STRING'].split('&')[2]
            product_name = product_name_str.split('=')[1]
        except Exception as ex:
            print('Exception is {}'.format(ex))

        print(uuttype, sn, product_name)
        is_display = ''
        test_info = ''
        # 链接sqlist3数据库
        self.conn_db()
        if uuttype and sn and product_name:
            is_display = ''

            sql = '''insert into test_info (uuttype,sn,product_name,date) values
                    ('{}','{}','{}','{}')
                    '''.format(uuttype, sn, product_name, datetime.datetime.now().strftime('%Y-%m-%d'))
            self.update_info(update_sql=sql)

        else:
            is_display = 'none'

        search_sql = '''select * from test_info'''
        search_result = self.search_info(search_sql=search_sql)
        for e_result in search_result:
            print(e_result)
            test_info += """
                <li>{}--{}---{}---{}---{}</li>
            """.format(e_result[0], e_result[1], e_result[2], e_result[3], e_result[4])

        # 断开sqlist3数据库链接
        self.close_db()

        response_content = self.read_template(temp_file='show_edit_page.html')

        yield response_content

    def ajax_test_handle(self):
        status = '200 OK'
        response_headers = [('Content-type', 'application/json;charset=UTF-8')]
        self.start_respone(status, response_headers)
        # 链接sqlist3数据库
        self.conn_db()

        # 获取 user 表的所有信息
        my_user_sql = '''select * from users'''
        search_users_result = self.search_info(search_sql=my_user_sql)
        my_user_result = []
        for e_result in search_users_result:
            print(e_result)
            my_user_result.append(e_result)

        # 获取 test 表的所有信息
        my_test_sql = '''select * from test_info'''
        search_test_result = self.search_info(search_sql=my_test_sql)
        my_test_result = []
        for e_result in search_test_result:
            print(e_result)
            my_test_result.append(e_result)

        # 断开sqlist3数据库链接
        self.close_db()

        respones_content = {'status': 'ok',
                            'test': my_test_result,
                            'user': my_user_result
                            }
        return json.dumps(respones_content)

    def show_test_info_update(self):
        status = '200 OK'
        response_headers = [('Content-type', 'application/json;charset=UTF-8')]
        self.start_respone(status, response_headers)
        print(self.environ['QUERY_STRING'])
        id = ''
        try:
            id = self.environ['QUERY_STRING'].split('=')[1]
            print(id)
        except Exception as ex:
            print('Exception is {}'.format(ex))

        # 链接sqlist3数据库
        self.conn_db()

        search_sql = '''select * from test_info where id ="{}" '''.format(id)
        search_result = self.search_info(search_sql=search_sql)
        result = []
        for e_result in search_result:
            print(e_result)
            result.append(e_result)

        # 断开sqlist3数据库链接
        self.close_db()

        respones_content = {'status': 'ok',
                            'result': result
                            }
        return json.dumps(respones_content)


urls = {
    '/': 'get_index',
    '/index': 'get_index',
    '/show_edit_page': 'show_edit_page',  # 显示编辑页面
    '/show_test_update': 'show_test_update',  #

    '/show_test_info_update': 'show_test_info_update',  # 显示test 表某条信息
    '/test_info_update': 'test_info_update',  # 修改test 表的信息
    '/user_info_update': 'user_info_update',  # 修改user 表的信息
    '/ajax_test_handle': 'ajax_test_handle'
}


def my_application(environ, start_respone):
    my_app = MyApp(environ, start_respone)
    path = environ['PATH_INFO']
    method = environ['REQUEST_METHOD']
    print(path, method)
    # print(environ)

    # 通过字典匹配URL，获取并执行相应的函数
    for urls_key, func_name in urls.items():
        print(path, urls_key)
        m = re.match('^' + path + '$', urls_key)
        if m:
            # print(m.group())
            if hasattr(my_app, func_name):
                g = getattr(my_app, func_name)
                return g()
        if path.startswith('/static'):
            return my_app.read_static(path)
    else:
        return getattr(my_app, 'no_find')()


######################################################
def my_test_app(environ, start_respone):
    path = environ['PATH_INFO']
    method = environ['REQUEST_METHOD']
    print(path, method)

    status = '200 OK'
    response_headers = [('Content-type', 'text/html')]
    start_respone(status, response_headers)

    dic = {'name': 'name', 'no': 'no'}
    html = 'okokokok!!'

    return [json.dumps(dic)]
    # return html
